package txt2mysql;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

public class Txt2MySQL1 {

    private DBUtil db;

    public Txt2MySQL1(){
        db = new DBUtil();
    }

    private  void parseTxt(String path, List<String> column,String limit_date,String table) {
        List<String> result = new ArrayList<>();
        File file = new File(path);
        try {
            SimpleDateFormat format = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss +0800", Locale.US);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while ((s = br.readLine()) != null) {//使用readLine方法，一次读一行
                List<String> one = new ArrayList<>();
                String tmp=s;
                column.forEach(c -> {
                    if (tmp.contains(c)){
                        try {
                            String t=tmp.split(c+"=")[1];
                            String c_s="";
                            if (t.contains("&")){
                                c_s=t.substring(0,t.indexOf("&"));
                            }else if (t.contains("\"")){
                                c_s=t.substring(0,t.indexOf("\""));
                            }
                            one.add("'"+c_s+"'");
                        }catch (ArrayIndexOutOfBoundsException e){

                        }
                    }else {
                        one.add("''");
                    }
                });
                if (one.size()==column.size()){
                    result.add("("+String.join(",",one)+")");
                }
                if (result.size()>2000){
                    String SQL="insert into "+table+" (`"+String.join("`,`",column)+"`) values "+String.join(",",result);
                    db.CUD(SQL);
                    result.clear();
                }
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (result.size()>0){
            System.out.println("go to the last >>>");
            //最后result若是没有到2w 则将其入库
            String SQL="insert into "+table+" (`"+String.join("`,`",column)+"`) values "+String.join(",",result);
            db.CUD(SQL);
        }
    }

    public void Data2MySQL(String path,List<String> column,String date){
        //先创建表结构
        String table =CreateTime(column);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String start=df.format(new Date());
        System.out.println("开始入库:"+start);
        parseTxt(path,column,date,table);
        String end=df.format(new Date());
        System.out.println("入库完成:"+end);
    }

    private String CreateTime(List<String> table_filed){
        SimpleDateFormat df = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");//设置日期格式
        String prix=df.format(new Date());
        System.out.println("创建表>>>"+"step_"+prix);
        String sql="CREATE TABLE `step_"+prix+"` (\n" +
                "  `id` int(11) NOT NULL AUTO_INCREMENT,\n" +
                String.join(",",table_filed.stream().map( f -> {
                    if (f.contains("|")&&f.split("\\|")[1].equals("text"))
                        return "`"+f.split("\\|")[0]+"` text CHARACTER SET utf8 DEFAULT NULL";
                    return "`"+f+"` varchar(255) CHARACTER SET utf8 DEFAULT NULL";
                } ).collect(Collectors.toList()))+
                ",  PRIMARY KEY (`id`)\n" +
                ") ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;";
        System.out.println(sql);
        db.CUD(sql);
        System.out.println("表创建完成");
        return "step_"+prix;
    }

    /**
     * 日期格式字符串转换成时间戳
     *
     * @param dateStr 字符串日期
     * @param sdf  如：yyyy-MM-dd HH:mm:ss
     * @return
     */
    private String Date2TimeStamp(String dateStr,SimpleDateFormat sdf) {
        try {
            return String.valueOf(sdf.parse(dateStr).getTime() / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
